package com.ruoyi.info.userController;

import com.ruoyi.chat.domain.FhChatFriend;
import com.ruoyi.chat.service.IFhChatFriendService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.index.domain.FhIndexPostinfo;
import com.ruoyi.index.service.IFhIndexPostinfoService;
import com.ruoyi.info.domain.*;
import com.ruoyi.info.service.*;
import com.ruoyi.system.domain.FhUser;
import com.ruoyi.system.service.IFhUserService;
import com.ruoyi.tokenTools.UserLoginToken;
import com.test.aop.UserThreadLocal;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * 用户信息Controller
 * 
 * @author ruoyi
 * @date 2024-11-09
 */
@Api(tags = "用户信息")
@RestController
@RequestMapping("/info/userUser")
public class UserFhInfoUserController extends BaseController
{
    //获取过期时间
    @Value("${token.expireTime}")
    private Long expireTime;

    @Value("${hxim.appkey}")
    private String appkey;

    @Value("${hxim.ClientID}")
    private String ClientID;

    @Value("${hxim.ClientSecret}")
    private String ClientSecret;



    @Autowired
    private IFhInfoUserService fhInfoUserService;

    @Autowired
    private IFhInfoUserinterestService fhInfoUserinterestService;

    @Autowired
    private IFhInfoFishpointService iFhInfoFishpointService;

    @Autowired
    private IFhInfoCatchrecordService fhInfoCatchrecordService;

    @Autowired
    private IFhInfoInterestService fhInfoInterestService;

    @Autowired
    private IFhInfoMyspaceService fhInfoMyspaceService;

    @Autowired
    private IFhInfoRankrecordService fhInfoRankrecordService;

    @Autowired
    private IFhInfoLocationService fhInfoLocationService;

    @Autowired
    private IFhUserService iFhUserService;

    @Autowired
    private IFhChatFriendService fhChatFriendService;


    @Autowired
    private IFhInfoExperienceService fhInfoExperienceService;

    @Autowired
    private IFhIndexPostinfoService fhIndexPostinfoService;

    /**
     * 新增用户兴趣点，钓鱼位置，钓鱼水平
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("提交兴趣点，位置，钓鱼水平")
    @Log(title = "提交兴趣点，位置，钓鱼水平", businessType = BusinessType.INSERT)
    @Transactional
    @PostMapping
    public R<String> addInterestLocationLevel(InterestLocationLevelDto interestLocationLevelDto)
    {
        try {
            Long userId = UserThreadLocal.getUser();
            FhUser fhUser = iFhUserService.selectFhUserById(userId);

            String address = interestLocationLevelDto.getAddress();
            String fhInfoUserinterestS = interestLocationLevelDto.getFhInfoUserinterestS();
            String longitude = interestLocationLevelDto.getLongitude();
            String latitude = interestLocationLevelDto.getLatitude();
            String level = interestLocationLevelDto.getLevel();

            //插入用户定位位置
            FhInfoLocation fhInfoLocation = new FhInfoLocation();
            fhInfoLocation.setUserId(userId);
            fhInfoLocation.setLocationName(address);
            fhInfoLocation.setLongitude(longitude);
            fhInfoLocation.setLatitude(latitude);
            fhInfoLocationService.insertFhInfoLocation(fhInfoLocation);
            //插入用户钓鱼水平,性别
            String gender = iFhUserService.selectFhUserById(userId).getGender();
            FhInfoUser fhInfoUser = new FhInfoUser();
            fhInfoUser.setUserId(userId);
            fhInfoUser.setLevel(level);
            fhInfoUser.setGender(gender);
            fhInfoUser.setPhone(fhUser.getPhone());
            fhInfoUser.setCrateTime(new Date());
            fhInfoUser.setAddress(fhInfoLocation.getLocationName());
            fhInfoUser.setInterests(fhInfoUserinterestS);
            fhInfoUserService.insertFhInfoUser(fhInfoUser);

            //初始化用户捕获表，排名表，我的空间表
            FhInfoCatchrecord fhInfoCatchrecord = new FhInfoCatchrecord();
            fhInfoCatchrecord.setUserId(userId);
            fhInfoCatchrecord.setCatchNum(0L);
            fhInfoCatchrecord.setCatchType(0L);
            fhInfoCatchrecord.setFishPoind(0L);
            fhInfoCatchrecordService.insertFhInfoCatchrecord(fhInfoCatchrecord);
            FhInfoRankrecord fhInfoRankrecord = new FhInfoRankrecord();
            fhInfoRankrecord.setUserId(userId);
            fhInfoRankrecord.setFriendRank(0L);
            fhInfoRankrecord.setAreaRank(0L);
            fhInfoRankrecordService.insertFhInfoRankrecord(fhInfoRankrecord);
            FhInfoMyspace fhInfoMyspace = new FhInfoMyspace();
            fhInfoMyspace.setUserId(userId);
            fhInfoMyspace.setPostNum(0L);
            fhInfoMyspace.setRecentlyView(0L);
            fhInfoMyspaceService.insertFhInfoMyspace(fhInfoMyspace);
            return R.ok("提交成功");
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 获取用户信息详细信息
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("获取用户信息详细信息")
    @GetMapping()
    public R<FhInfoUserVo> getInfo( )
    {
        try {
            FhInfoUserVo fhInfoUserVo = new FhInfoUserVo();

            Long userId = com.test.aop.UserThreadLocal.getUser();
            FhInfoUser fhInfoUser1 = new FhInfoUser();
            fhInfoUser1.setUserId(userId);
            FhInfoUser fhInfoUser = fhInfoUserService.selectFhInfoUserList(fhInfoUser1).get(0);
            BeanUtils.copyProperties(fhInfoUser,fhInfoUserVo);
            //计算用户当前经验百分比
            Long nowExperience = fhInfoUser.getExperience();
            Long grade = fhInfoUser.getGrade();
            FhInfoExperience fhInfoExperience = fhInfoExperienceService.selectFhInfoExperienceById(grade + 1);
            Long experienceMax = fhInfoExperience.getExperienceMax();
            Long  schedule =  (nowExperience*100)/ (experienceMax);
            fhInfoUserVo.setExperience(schedule);
            fhInfoUserVo.setNowExperience(nowExperience);
            fhInfoUserVo.setMaxExperience(experienceMax);
            return R.ok(fhInfoUserVo);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 修改用户信息
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("修改用户信息")
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public R<String> edit(FhInfoUser fhInfoUser)
    {
        try {
            Long userId = UserThreadLocal.getUser();
            //根据用户id查找用户信息
            FhInfoUser fhInfoUser1 = fhInfoUserService.selectFhInfoUserByUserId(userId);
            fhInfoUser.setId(fhInfoUser1.getId());
            fhInfoUser.setUserId(userId);
            fhInfoUserService.updateFhInfoUser(fhInfoUser);
            return R.ok("修改成功");
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 删除账号
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("删除账号")
    @Log(title = "删除账号", businessType = BusinessType.DELETE)
    @DeleteMapping()
    @Transactional(rollbackFor = Exception.class)
    public R<String> removeUser()
    {
        try {
            Long userId = UserThreadLocal.getUser();
            //删除用户信息
            FhInfoUser fhInfoUser = new FhInfoUser();
            fhInfoUser.setUserId(userId);

            Long id = fhInfoUserService.selectFhInfoUserList(fhInfoUser).get(0).getId();
            fhInfoUserService.deleteFhInfoUserById(id);
            //删除用户账号
            iFhUserService.deleteFhUserById(userId);
            return R.ok("删除账号成功");
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 查询渔获记录
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("查询渔获记录")
    @GetMapping("/catchRecord")
    public R<FhInfoCatchrecord> catchRecord()
    {
        try {
            FhInfoCatchrecord fhInfoCatchrecord = new FhInfoCatchrecord();
            fhInfoCatchrecord.setUserId(UserThreadLocal.getUser());
            List<FhInfoCatchrecord> list = fhInfoCatchrecordService.selectFhInfoCatchrecordList(fhInfoCatchrecord);
            return R.ok(list.get(0));
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 查询我的空间列表
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("查询我的空间")
    @GetMapping("/mySpace")
    public R<FhInfoMyspaceVo> mySpace()
    {
        try{
            FhInfoMyspaceVo fhInfoMyspaceVo = new FhInfoMyspaceVo();

            FhInfoMyspace fhInfoMyspace = new FhInfoMyspace();
            Long userId = UserThreadLocal.getUser();
            fhInfoMyspace.setUserId(userId);
            List<FhInfoMyspace> list = fhInfoMyspaceService.selectFhInfoMyspaceList(fhInfoMyspace);
            BeanUtils.copyProperties(list.get(0),fhInfoMyspaceVo);
            //根据用户id查询用户最近一次的发布记录;
            FhIndexPostinfo fhIndexPostinfo = new FhIndexPostinfo();
            fhIndexPostinfo.setUserId(userId);
            List<FhIndexPostinfo> fhIndexPostinfoList = fhIndexPostinfoService.selectFhIndexPostinfoList(fhIndexPostinfo);
            if(fhIndexPostinfoList.isEmpty()){
                return R.ok(fhInfoMyspaceVo);
            }
            Long postId = fhIndexPostinfoList.get(0).getId();
            String postImages = fhIndexPostinfoService.selectFhIndexPostinfoById(postId).getPostImages();
            fhInfoMyspaceVo.setPostImages(postImages);

            list.get(0).setPostImages(postImages);
            fhInfoMyspaceService.updateFhInfoMyspace(list.get(0));

            return R.ok(fhInfoMyspaceVo);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 查询排名记录列表
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("查询排名记录列表")
    @GetMapping("/rankRecord")
    public R<RankDto> rankRecord()
    {
        try{
            //根据用户id获取用户地址，用户捕获数，c查询地区排名
            Long userId = UserThreadLocal.getUser();
            FhInfoUser fhInfoUser = fhInfoUserService.selectFhInfoUserByUserId(userId);
            FhInfoUser fhInfoUserByAddress = new FhInfoUser();
            fhInfoUserByAddress.setAddress(fhInfoUser.getAddress());

            FhInfoCatchrecord fhInfoCatchrecordByUserid = fhInfoCatchrecordService.selectFhInfoCatchrecordByUserId(userId);
            Long userCatchNum = fhInfoCatchrecordByUserid.getCatchNum();

            /**
             * 计算用户地区排名
             */
            ArrayList<RankCatchrecordDto> rankCatchrecordDtoArrayList = new ArrayList<>();
            //根据用户地址获取到用户信息列表
            List<FhInfoUser> fhInfoUserList = fhInfoUserService.selectFhInfoUserList(fhInfoUserByAddress);
            for (int i = 0; i < fhInfoUserList.size(); i++) {
                Long userId1 = fhInfoUserList.get(i).getUserId();
                FhInfoCatchrecord fhInfoCatchrecord = fhInfoCatchrecordService.selectFhInfoCatchrecordByUserId(userId1);
                RankCatchrecordDto rankCatchrecordDto = new RankCatchrecordDto();
                rankCatchrecordDto.setUserId(userId1);
                rankCatchrecordDto.setUserImage(fhInfoUserList.get(i).getImage());
                rankCatchrecordDto.setCatchNum(fhInfoCatchrecord.getCatchNum());
                rankCatchrecordDtoArrayList.add(rankCatchrecordDto);
            }
            //对获取到的用户地区捕获记录进行排序，计算出用户的地区排名
            rankCatchrecordDtoArrayList.sort(new Comparator<RankCatchrecordDto>() {
                @Override
                public int compare(RankCatchrecordDto o1, RankCatchrecordDto o2) {
                    Long catchNum = o1.getCatchNum();
                    Long catchNum1 = o2.getCatchNum();
                    return catchNum1.compareTo(catchNum);
                }
            });
            int userAreaRank = 1;
            //计算用户地区排名
            for (int i = 0; i < rankCatchrecordDtoArrayList.size(); i++) {
                if(rankCatchrecordDtoArrayList.get(i).getCatchNum() != userCatchNum){
                    userAreaRank+=1;
                }else {
                    break;
                }
            }


            /**
             * 计算用户好友排名
             */
            List<RankCatchrecordDto> rankCatchrecordDtoFriendList = new ArrayList<>();
            //根据用户id获取到用户好友列表
            FhChatFriend fhChatFriend = new FhChatFriend();
            fhChatFriend.setUserId(userId);
            List<FhChatFriend> fhChatFriends = fhChatFriendService.selectFhChatFriendList(fhChatFriend);
            for (int i = 0; i < fhChatFriends.size(); i++) {
                Long friendId = fhChatFriends.get(i).getFriendId();
                FhInfoCatchrecord fhInfoCatchrecord = fhInfoCatchrecordService.selectFhInfoCatchrecordByUserId(friendId);
                FhInfoUser fhInfoUser1 = fhInfoUserService.selectFhInfoUserByUserId(friendId);
                RankCatchrecordDto rankCatchrecordDto = new RankCatchrecordDto(friendId,fhInfoCatchrecord.getCatchNum(),fhInfoUser1.getImage());
                rankCatchrecordDtoFriendList.add(rankCatchrecordDto);
            }
            rankCatchrecordDtoFriendList.add(new RankCatchrecordDto(Long.valueOf(userId),fhInfoCatchrecordByUserid.getCatchNum(),fhInfoUser.getImage()));
            //对获取到的用户地区捕获记录进行排序，计算出用户的好友排名
            rankCatchrecordDtoFriendList.sort(new Comparator<RankCatchrecordDto>() {
                @Override
                public int compare(RankCatchrecordDto o1, RankCatchrecordDto o2) {
                    Long catchNum = o1.getCatchNum();
                    Long catchNum1 = o2.getCatchNum();
                    return catchNum1.compareTo(catchNum);
                }
            });
            int userFriendRank = 1;
            //计算用户好友排名
            for (int i = 0; i < rankCatchrecordDtoFriendList.size(); i++) {
                if(rankCatchrecordDtoFriendList.get(i).getCatchNum()!=userCatchNum){
                    userFriendRank+=1;
                }else {
                    break;
                }
            }
            //更新用户排名表
            FhInfoRankrecord fhInfoRankrecord = new FhInfoRankrecord();
            fhInfoRankrecord.setUserId(userId);
            Long userAreaRank1 = (long) userAreaRank;
            fhInfoRankrecord.setAreaRank(userAreaRank1);
            Long userFriend1 = (long) userFriendRank;
            fhInfoRankrecord.setFriendRank(userFriend1);
            fhInfoRankrecord.setCrateTime(new Date());
            fhInfoRankrecordService.updateFhInfoRankrecordByUserId(fhInfoRankrecord);

            //返回数据，地区排名，地区排名列表，好友排名，好友排名列表
            RankDto rankDto = new RankDto();
            rankDto.setAreaRank(userAreaRank);
            if(rankCatchrecordDtoArrayList.size()==1){
                rankDto.setRankCatchrecordAreaList(rankCatchrecordDtoArrayList.subList(0,1));
            }else if(rankCatchrecordDtoArrayList.size()==2){
                rankDto.setRankCatchrecordAreaList(rankCatchrecordDtoArrayList.subList(0,2));
            } else if(rankCatchrecordDtoArrayList.size()>=3){
                rankDto.setRankCatchrecordAreaList(rankCatchrecordDtoArrayList.subList(0,3));
            }
            rankDto.setFriendRank(userFriendRank);
            if(rankCatchrecordDtoFriendList.size()==1){
                rankDto.setRankCatchrecordFriendList(rankCatchrecordDtoFriendList.subList(0,1));
            }else if(rankCatchrecordDtoFriendList.size()==2){
                rankDto.setRankCatchrecordFriendList(rankCatchrecordDtoFriendList.subList(0,2));
            } else if(rankCatchrecordDtoFriendList.size()>=3){
                rankDto.setRankCatchrecordFriendList(rankCatchrecordDtoFriendList.subList(0,3));
            }


            return R.ok(rankDto);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }



//    向环信im注册用户




}
